package com.fce.boc.provider;

import com.alibaba.fastjson.JSON;
import com.fce.boc.bean.ReturnMsg;
import com.fce.boc.bean.BocTransaction;
import com.fce.boc.service.BocTransactionService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "bocDirectQueue", autoDelete = "false"),
        exchange = @Exchange(value = "directExchange", type = ExchangeTypes.DIRECT),
        key = "bocRoutingKey"))
public class BocProvider {
    Logger LOG = LoggerFactory.getLogger(BocProvider.class);

    @Autowired
    private BocTransactionService bocTransactionService;

    @RabbitHandler
    public void receiverMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        LOG.info("class:{}","BocProvider");

        // 将JSON字符串转换为实体类对象
        BocTransaction bocTransaction = JSON.parseObject(msg, BocTransaction.class);
        System.out.println(bocTransaction.toString());

        //保存boc交易数据
        ReturnMsg result = bocTransactionService.addTransaction(bocTransaction);

        if(ReturnMsg.success().getCode().equals(result.getCode())){
            //手动签收  channel.basicAck(消息唯一标识,是否批量签收);
            LOG.info("success: {}",msg);
            channel.basicAck(deliveryTag,false);
            return;
        }

    }
}
